package com.zht.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.poi.excel.ExcelReader;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.MapUtils;
import com.alibaba.fastjson.JSON;
import com.zht.annotation.AddUserAnnotation;
import com.zht.annotation.ZhtTestAnnotation;
import com.zht.entity.*;
import com.zht.result.AjaxResult;
import com.zht.service.SelectSpeedList;
import com.zht.service.SendMessageService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;

@RestController
@RequestMapping("zht")
public class SendMessageController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    SendMessageService sendMessageService;

    @Autowired
    SelectSpeedList selectSpeedList;

    @GetMapping("testSendMessage")
    public String testSendMessage(){
        return "失败";
//        ApiResult result = sendMessageService.testSendMessage("1003");
//        return result;
    }

    /**
     * 集团-获取速率集合
     * @return
     */
    @GetMapping("getSpeedList")
    public SelectSpeedListVo getSpeedList(){
        SelectSpeedListVo listVo = new SelectSpeedListVo();
        // 查询速率集合并返回数据
        List<String> speedList = selectSpeedList.getSpeedList();
        listVo.setSpeedList(speedList);
        return listVo;
    }

    /**
     * 集团-通过速率获取对应的服务费
     * @param speed
     * @return
     */
    @GetMapping("getExpenseBySpeed")
    public Integer getExpenseBySpeed(@RequestParam("speed") String speed){
        if (StringUtils.isBlank(speed)){
            return 1;
        }
       Integer expense =  selectSpeedList.getExpenseBySpeed(speed);
       return expense;
    }

    /**
     * 集团-excel文件导入
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("uploadClique")
    public String uploadExcel(@RequestParam("uplink") String uplink ,@RequestParam("file") MultipartFile file) throws IOException {
        // 上传人非空校验
        if (StringUtils.isBlank(uplink)){
            return "上传人为空!";
        }
        // 判断文件是否为空
        if (ObjectUtil.isNull(file)){
            return "传入的文件为空";
        }
        // 获取文件名判断是否是excel
        String filename = file.getOriginalFilename();
        if (StringUtils.isBlank(filename)){
            return "传入的文件名为空";
        }
        String fileSuffix = filename.substring(filename.lastIndexOf(".") + 1);
        if (!fileSuffix.equals("xls") && !fileSuffix.equals("xlsx")){
            return "文件格式不正确，请检查后重新上传！";
        }
        selectSpeedList.uploadExcel(uplink,file);
        return "上传成功";
    }

    /**
     * 集团-excel导出
     */
    @PostMapping("exportClique")
    public void export(HttpServletResponse response, CliqueSdWan cliqueSdWan) throws IOException{

        List<CliqueSdWan> list = selectSpeedList.selectCaononNumList(cliqueSdWan);
        response.setHeader("content-Type", "application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename=orders.xls");
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), CliqueSdWan.class, list);
        workbook.write(response.getOutputStream());

    }

    /**
     * 互联网-excel上传
     * @param uplink
     * @param file
     * @return
     */
    @PostMapping("uploadInternet")
    public String uploadInternet(@RequestParam("uplink") String uplink ,@RequestParam("file") MultipartFile file) throws IOException {
        // 上传人非空校验
        if (StringUtils.isBlank(uplink)){
            return "上传人为空!";
        }
        // 判断文件是否为空
        if (ObjectUtil.isNull(file)){
            return "传入的文件为空";
        }
        // 获取文件名判断是否是excel
        String filename = file.getOriginalFilename();
        if (StringUtils.isBlank(filename)){
            return "传入的文件名为空";
        }
        String fileSuffix = filename.substring(filename.lastIndexOf(".") + 1);
        if (!fileSuffix.equals("xls") && !fileSuffix.equals("xlsx")){
            return "文件格式不正确，请检查后重新上传！";
        }
        selectSpeedList.uploadInternet(file,uplink);
        return "上传成功!";
    }


    /**
     * 集团-excel文件下载导出
     * @param response
     * @throws IOException
     */
    @GetMapping("download")
    public void downloadFailedUsingJson(HttpServletResponse response) throws IOException {
        List<CliqueSdWan> list = selectSpeedList.list();
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("测试EasyExcel", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            // 这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream(), CliqueSdWan.class).autoCloseStream(Boolean.FALSE).sheet("模板")
                    .doWrite(list);
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = MapUtils.newHashMap();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }
    }

    /**
     * 查询互联网专线数据集合
     * @return
     */
    @GetMapping("getInternetDataList")
    public InternetLineVo getInternetDataList(){
        InternetLineVo internetLineVo = new InternetLineVo();
        // 普通接入结果集
        List<String> normalList =  selectSpeedList.getNormalListList();
        // 速率结果集
        List<String> speedList =  selectSpeedList.getSpeedListList();
        // 接入方式结果集
        List<String> accessModeList =  selectSpeedList.getAccessModeListList();
        // 接入层级结果集
        List<String> accessLevelList =  selectSpeedList.getAccessLevelListList();
        internetLineVo.setNormal(normalList);
        internetLineVo.setSpeed(speedList);
        internetLineVo.setAccessMode(accessModeList);
        internetLineVo.setAccessLevel(accessLevelList);
        return internetLineVo;
    }

    @ZhtTestAnnotation
    @GetMapping("/testAnnotation")
    public String testAnnotation(){
//        redisTemplate.delete("test");
//        redisTemplate.opsForList().leftPush("testList",1);
//        Object test = redisTemplate.opsForValue().get("test");
        System.out.println("测试方法执行完毕");
        return "测试方法执行完毕";
    }

    @AddUserAnnotation
    @PostMapping("/addUser")
    public UserEntity addUser(@RequestBody UserEntity userEntity) throws Exception {
        if (userEntity == null){
            throw new Exception("数据为空");
        }
        // 返回
        return userEntity;
    }


}
